/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiof.moraa.server.service;

import com.hiof.moraa.mapping.TblRoute;
import com.hiof.moraa.server.dao.RouteDAO;
import com.hiof.moraa.server.service.model.RouteInfo;
import com.hiof.moraa.server.service.model.RouteInfoCollection;
import com.hiof.moraa.server.service.model.RouteStatus;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Bergy
 */
@Transactional(readOnly = true)
public class RouteServiceImp implements RouteService {

    RouteDAO dao;

    public void setDao(RouteDAO dao) {
        this.dao = dao;
    }

    @Override
    public RouteInfoCollection getRouteInfoCollection(String username) {
        RouteInfoCollection result = new RouteInfoCollection();
        List<TblRoute> tblRoutes = dao.getTblRoute(username);
        for (TblRoute tblRoute : tblRoutes) {
            RouteInfo info = new RouteInfo(tblRoute.getId(), tblRoute.getName(), tblRoute.getDescription());

            info.setStatus(getRouteStatus(username, tblRoute));
            result.addRouteInfoElement(info);
        }
        return result;
    }

    @Override
    public String getMapPath(int routeId) {
        return dao.getTblRoute(routeId).getMapPath();
    }

    @Override
    public String getMapPublicPath(int routeId) {
        return dao.getTblRoute(routeId).getPublicMapPath();
    }

    private RouteStatus getRouteStatus(String username, TblRoute tblRoute) {
        //TODO: Make it more clear here
        Timestamp currentTime = new Timestamp(new java.util.Date().getTime());
        Date startTimeDate = tblRoute.getStartTime();
        Date endTime = (Date) startTimeDate.clone();

        Calendar cal = Calendar.getInstance();
        cal.setTime(endTime);
        cal.add(Calendar.DATE, 1);
        endTime = cal.getTime();
        //TODO: Do real one here, routeID = 2 will be on going for test
        if (currentTime.before(startTimeDate)) {
            return RouteStatus.REGISTERED;
        } else if (currentTime.after(endTime)) {
            return RouteStatus.FINISHED;
        } else {
            return RouteStatus.ONGOING;
        }
    }
}
